<template>
  <el-dialog
    :visible.sync="visible"
    :title="!dataForm.id ? $t('add') : $t('update')"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
  >
    <el-form
      :model="dataForm"
      :rules="dataRule"
      ref="dataForm"
     
      @keyup.enter.native="dataFormSubmitHandle()"
      label-width="120px"
    >
      <el-row :gutter="20">
        <el-col :span="12" :offset="0">
          <el-form-item  label="用户名称">
            <el-input
              v-model="dataForm.userName"
              :readonly="dataForm.id"
              :placeholder="$t('user.username')"
            ></el-input>
          </el-form-item>
        </el-col>
        <!-- <el-col :span="12" :offset="0">
          <el-form-item prop="deptName" label="性别">
            <el-radio-group v-model="dataForm.deptName">
              <el-radio :label="0">男</el-radio>
              <el-radio :label="1">女</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col> -->
        <el-col :span="12" :offset="0">
          <el-form-item  label="授权手机号">
            <el-input
            :readonly="dataForm.id"
              v-model="dataForm.authorizationPhone"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12" :offset="0">
          <el-form-item label="预约手机号">
            <el-input
              :readonly="dataForm.id"
              v-model="dataForm.reservationPhone"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12" :offset="0">
          <el-form-item label="站点名称">
            <el-autocomplete
               style="width:100%"
              popper-class="my-autocomplete"
              v-model="dataForm.storeName"
              :fetch-suggestions="querySearch"
              placeholder="请输入内容"
              @select="handleSelect"
              @input="changeData"
            >
              <i
                class="el-icon-edit el-input__icon"
                slot="suffix"
                @click="handleIconClick"
              >
              </i>
              <template slot-scope="{ item }">
                <div class="name">{{ item.stationName }}</div>
              </template>
            </el-autocomplete>
          </el-form-item>
        </el-col>
        <el-col :span="12" :offset="0">
          <el-form-item  label="经销商位置">
            <el-input
              v-model="dataForm.storeAddress"
              readonly
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12" :offset="0">
          <el-form-item  label="联系人名称">
            <el-input
              v-model="dataForm.storeUsername"
              readonly
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12" :offset="0">
          <el-form-item  label="联系人电话" class="role-list">
            <el-input
              v-model="dataForm.storePhone"
              readonly
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12" :offset="0">
          <el-form-item  label="试驾车系">
            <el-autocomplete
              style="width:100%"
              popper-class="my-autocomplete"
              v-model="dataForm.reservationVdsName"
              :fetch-suggestions="querySearch2"
              placeholder="请输入内容"
              @select="handleSelect2"
            >
              <i
                class="el-icon-edit el-input__icon"
                slot="suffix"
                @click="handleIconClick2"
              >
              </i>
              <template slot-scope="{ item }">
                <div class="name">{{ item.vdsName }}</div>
              </template>
            </el-autocomplete>
          </el-form-item>
        </el-col>
        <!--  -->
        <el-col :span="12" :offset="0">
          <el-form-item prop="reservationStatus" label="状态" size="mini">
            <el-radio-group v-model="dataForm.reservationStatus">
              <el-radio label="0">隐藏</el-radio>
              <el-radio label="1">显示</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template slot="footer">
      <el-button @click="oncancel">{{ $t("cancel") }}</el-button>
      <el-button type="primary" @click="dataFormSubmitHandle()">{{
        $t("confirm")
      }}</el-button>
    </template>
  </el-dialog>
</template>

<script>
import debounce from "lodash/debounce";
import { isEmail, isMobile } from "@/utils/validate";
export default {
  data() {
    return {
      visible: false,
      roleList: [],
      restaurants: [],
      carList:[],//车型
      roleIdListDefault: [],
      recipientTips:[],//位置
      dataForm: {
        id: "",
        userName: "",
        authorizationPhone: "",
        reservationPhone: "",
        storeAddress: "",
        storeName: "",
        storeUsername: "",
        storePhone: "",
        reservationVdsId:"",
        reservationVdsName: "",
        reservationStatus:'1',
      },
    };
  },
  computed: {
    dataRule() {
      var validatePassword = (rule, value, callback) => {
        if (!this.dataForm.id && !/\S/.test(value)) {
          return callback(new Error(this.$t("validate.required")));
        }
        callback();
      };
      var validateConfirmPassword = (rule, value, callback) => {
        if (!this.dataForm.id && !/\S/.test(value)) {
          return callback(new Error(this.$t("validate.required")));
        }
        if (this.dataForm.password !== value) {
          return callback(new Error(this.$t("user.validate.confirmPassword")));
        }
        callback();
      };
      var validateEmail = (rule, value, callback) => {
        if (value && !isEmail(value)) {
          return callback(
            new Error(
              this.$t("validate.format", { attr: this.$t("user.email") })
            )
          );
        }
        callback();
      };
      var validateMobile = (rule, value, callback) => {
        if (value && !isMobile(value)) {
          return callback(
            new Error(
              this.$t("validate.format", { attr: this.$t("user.mobile") })
            )
          );
        }
        callback();
      };
      return {
        username: [
          {
            required: true,
            message: this.$t("validate.required"),
            trigger: "blur",
          },
        ],
        deptName: [
          {
            required: true,
            message: this.$t("validate.required"),
            trigger: "change",
          },
        ],
        password: [{ validator: validatePassword, trigger: "blur" }],
        confirmPassword: [
          { validator: validateConfirmPassword, trigger: "blur" },
        ],
        realName: [
          {
            required: true,
            message: this.$t("validate.required"),
            trigger: "blur",
          },
        ],
        email: [{ validator: validateEmail, trigger: "blur" }],
        mobile: [{ validator: validateMobile, trigger: "blur" }],
      };
    },
  },
  created() {
    this.handleChange();
  },
  methods: {
    oncancel(){
      this.visible = false
      this.$emit('canCle')
    },
    handleSelect2(item){
      this.dataForm.reservationVdsName = item.vdsName;
      this.dataForm.reservationVdsId = item.vdsCode
    },
    handleIconClick2(ev){
      console.log(ev,'这个又是啥玩意');
    },
    querySearch2(queryString, cb) {
      let params = {
        vds: queryString,
      };
      this.handleChange2(params,cb);
    },
     // 获取
     handleChange2(params,cb) {
       this.$http
        .get("/findbrandbranchvds/page", {
          params,
        })
        .then(res => {
          this.carList = res.data.data.list.map((item) => {
            return {
              vdsName: item.branchChn,
              vdsCode: item.branchCode,
              vdsId:item.branchId
            };
          });
          cb(this.carList)
        })
        .catch(() => {});
    },
     //@select 点击选中建议项时触发
     handleSelect(item) {
      this.dataForm.storeName = item.stationName
      this.dataForm.storePhone = item.phone;
      this.dataForm.storeAddress = item.address;
      this.dataForm.storeUsername = item.contacts;
    },
    //@input 在 Input 值改变时触发
    changeData(value){
      if(value!=''){
        this.handleChange()
      }
    },
    querySearch(queryString, cb) {
      let params = {
        stationName: queryString,
      };
      this.handleChange(params,cb);
      // cb(this.recipientTips);
     
    },
    createFilter(queryString) {
      return (restaurant) => {
        return (
          restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) ===
          0
        );
      };
    },
    handleIconClick(ev) {
      console.log(ev,'这个又是啥玩意');
    },
    // 获取
    handleChange(params,cb) {
       this.$http
        .get("/storemanage/page", {
          params,
        })
        .then(res => {
          this.recipientTips = res.data.data.list.map((item) => {
            return {
              stationName: item.stationName,
              phone:item.contactsNumber,
              contacts:item.contacts,
              address:item.address,
              id: item.id,

            };
          });
          cb(this.recipientTips)
        })
        .catch(() => {});
    },
    init() {
      this.visible = true;
      this.$nextTick(() => {
        this.$refs["dataForm"].resetFields();
        this.roleIdListDefault = [];
        // Promise.all([this.getRoleList()]).then(() => {
        if (this.dataForm.id) {
          this.getInfo();
        }
        // });
      });
    },

    // 获取信息
    getInfo() {
      this.$http
        .get(`/userreservation/${this.dataForm.id}`)
        .then(({ data: res }) => {
          if (res.code !== 0) {
            return this.$message.error(res.msg);
          }
          this.dataForm = {
            ...res.data,
          };
          this.dataForm.reservationStatus = String(this.dataForm.reservationStatus)
        })
        .catch(() => {});
    },
    // 表单提交
    dataFormSubmitHandle: debounce(
      function () {
        this.$refs["dataForm"].validate((valid) => {
          if (!valid) {
            return false;
          }
          let url
          if(!this.dataForm.id){
            url = 'userreservation/save'
          }else{
            url = 'userreservation/update';
          }
          this.$http.post(url, {
            ...this.dataForm,
          })
            .then(({ data: res }) => {
              if (res.code !== 0) {
                return this.$message.error(res.msg);
              }
              this.$message({
                message: this.$t("prompt.success"),
                type: "success",
                duration: 500,
                onClose: () => {
                  this.oncancel()
                  this.$emit("refreshDataList");
                },
              });
            })
            .catch(() => {});
        });
      },
      1000,
      { leading: true, trailing: false }
    ),
  },
};
</script>

<style lang="scss">
.my-autocomplete {
  li {
    line-height: normal;
    padding: 7px;

    .name {
      text-overflow: ellipsis;
      overflow: hidden;
    }
    .addr {
      font-size: 15px;
      padding: 0 3px;
      color: #111;
    }

    .highlighted .addr {
      color: #111;
    }
  }
}
.mod-sys__user {
  .role-list {
    .el-select {
      width: 100%;
    }
  }
}
</style>
